package header

import (
	"fmt"
	"regexp"
	"strings"
	"udp_tcp_client/sip/header/common"
	"udp_tcp_client/util"
)

// SIP用户信息
// Example："1011" <sip:1011@192.168.0.2>;tag=213788011b
type UserIpPort struct {
	DisplayName string           // 显示姓名
	URI         common.URIIpPort // RequestURI地址
	Arguments   common.Args      // 参数
}

func NewUserIpPort(displayName string, userName string, ip string, port int, arguments common.Args) (UserIpPort, error) {
	user := UserIpPort{}

	uri := common.URIIpPort{}
	uri.Scheme = util.SchemeSip
	uri.Username = userName
	uri.IP = ip
	uri.Port = port
	uri.Arguments = common.Args{}
	user.URI = uri

	user.Arguments = arguments
	user.DisplayName = displayName
	return user, nil
}

func parseUserIpPort(str string) (item UserIpPort, err error) {
	str = strings.TrimSpace(str)
	item = UserIpPort{}
	err = item.parse(str)
	return
}

// 字符串输出
func (u *UserIpPort) String() (result string) {
	//if len(u.DisplayName) > 0 {
	//	result += fmt.Sprintf(util.BACKSLASH+"%s"+util.BACKSLASH, u.DisplayName)
	//}
	result += fmt.Sprintf("<%s>%s", u.URI.String(), u.Arguments.String())
	return
}

// 获取用户名
func (u *UserIpPort) Username() string {
	return u.URI.Username
}

// 解析SIP用户
func (u *UserIpPort) parse(str string) (err error) {
	var uri common.URIIpPort
	result := nameDomainRegexp.FindStringSubmatch(str)
	if len(result) == 0 {
		if uri, err = common.NewURIIpPort(str); err != nil {
			return
		}
		u.URI = uri
		u.Arguments = common.ParseArgs("") // FIXME 这里可能也有参数
		return
	}
	u.DisplayName = strings.Trim(strings.TrimSpace(result[1]), util.BACKSLASH)
	if uri, err = common.NewURIIpPort(result[2]); err != nil {
		return
	}
	u.URI = uri
	u.Arguments = common.ParseArgs(result[3])
	return
}

var nameIpPortRegexp = regexp.MustCompile("^([^<]*)<([^>]+)>(.*)$")
